import React, { useEffect, useState, useRef } from 'react';
import { Canvas, useThree } from '@react-three/fiber';
import { OrbitControls, Grid } from '@react-three/drei';
import {
    Paper,
    Typography,
    Box,
    Button,
    Tooltip,
    IconButton,
    Menu,
    MenuItem,
    ListItemIcon,
    ListItemText
} from '@mui/material';
import {
    FileDownload as FileDownloadIcon,
    ViewInAr as ViewInArIcon
} from '@mui/icons-material';
import { exportModel } from './exporters/ModelExporter';

// 3D模型渲染组件
const ModelRenderer = ({ model }) => {
    const { camera } = useThree();

    useEffect(() => {
        camera.position.set(5, 5, 5);
        camera.lookAt(0, 0, 0);
    }, [camera]);

    // 如果没有模型数据，显示空场景
    if (!model || !model.geometry) {
        return (
            <>
                <ambientLight intensity={0.5} />
                <directionalLight position={[10, 10, 5]} intensity={1} />
                <Grid
                    args={[20, 20]}
                    cellSize={1}
                    cellThickness={0.5}
                    cellColor="#6f6f6f"
                    fadeDistance={30}
                />
                <OrbitControls makeDefault />
            </>
        );
    }

    // 渲染几何体模型
    const { geometry } = model;

    return (
        <>
            <ambientLight intensity={0.5} />
            <directionalLight position={[10, 10, 5]} intensity={1} />
            <Grid
                args={[20, 20]}
                cellSize={1}
                cellThickness={0.5}
                cellColor="#6f6f6f"
                sectionSize={5}
                sectionThickness={1}
                sectionColor="#9d4b4b"
                fadeDistance={30}
                fadeStrength={1.5}
                followCamera={false}
                infiniteGrid
            />
            <OrbitControls makeDefault />

            {/* 渲染主几何体 */}
            {geometry.type === 'cube' && (
                <mesh
                    position={[
                        geometry.position?.x || 0,
                        geometry.position?.y || 0,
                        geometry.position?.z || 0
                    ]}
                    rotation={[
                        geometry.rotation?.x || 0,
                        geometry.rotation?.y || 0,
                        geometry.rotation?.z || 0
                    ]}
                >
                    <boxGeometry
                        args={[
                            geometry.dimensions?.width || 1,
                            geometry.dimensions?.height || 1,
                            geometry.dimensions?.depth || 1
                        ]}
                    />
                    <meshStandardMaterial color={geometry.color || '#3366FF'} />
                </mesh>
            )}

            {geometry.type === 'sphere' && (
                <mesh
                    position={[
                        geometry.position?.x || 0,
                        geometry.position?.y || 0,
                        geometry.position?.z || 0
                    ]}
                    rotation={[
                        geometry.rotation?.x || 0,
                        geometry.rotation?.y || 0,
                        geometry.rotation?.z || 0
                    ]}
                >
                    <sphereGeometry
                        args={[
                            geometry.dimensions?.radius || 1,
                            geometry.dimensions?.segments || 32,
                            geometry.dimensions?.segments || 32
                        ]}
                    />
                    <meshStandardMaterial color={geometry.color || '#3366FF'} />
                </mesh>
            )}

            {/* 渲染额外的几何体对象 */}
            {model.additionalObjects && model.additionalObjects.map((obj, index) => (
                obj.type === 'cube' ? (
                    <mesh
                        key={`additional-${index}`}
                        position={[
                            obj.position?.x || 0,
                            obj.position?.y || 0,
                            obj.position?.z || 0
                        ]}
                        rotation={[
                            obj.rotation?.x || 0,
                            obj.rotation?.y || 0,
                            obj.rotation?.z || 0
                        ]}
                    >
                        <boxGeometry
                            args={[
                                obj.dimensions?.width || 1,
                                obj.dimensions?.height || 1,
                                obj.dimensions?.depth || 1
                            ]}
                        />
                        <meshStandardMaterial color={obj.color || '#3366FF'} />
                    </mesh>
                ) : obj.type === 'sphere' ? (
                    <mesh
                        key={`additional-${index}`}
                        position={[
                            obj.position?.x || 0,
                            obj.position?.y || 0,
                            obj.position?.z || 0
                        ]}
                        rotation={[
                            obj.rotation?.x || 0,
                            obj.rotation?.y || 0,
                            obj.rotation?.z || 0
                        ]}
                    >
                        <sphereGeometry
                            args={[
                                obj.dimensions?.radius || 1,
                                obj.dimensions?.segments || 32,
                                obj.dimensions?.segments || 32
                            ]}
                        />
                        <meshStandardMaterial color={obj.color || '#3366FF'} />
                    </mesh>
                ) : null
            ))}
        </>
    );
};

// 3D模型预览组件
const ModelViewer = ({ model, height = 400, showInfo = true }) => {
    const [downloadMenuAnchor, setDownloadMenuAnchor] = useState(null);
    const [downloadInProgress, setDownloadInProgress] = useState(false);

    // 打开下载菜单
    const handleOpenDownloadMenu = (event) => {
        setDownloadMenuAnchor(event.currentTarget);
    };

    // 关闭下载菜单
    const handleCloseDownloadMenu = () => {
        setDownloadMenuAnchor(null);
    };

    // 下载JSON格式
    const downloadJsonModel = () => {
        if (!model) return;
        handleCloseDownloadMenu();

        try {
            // 构建导出数据
            const exportData = {
                name: model.name || '未命名模型',
                description: model.description || '',
                geometry: model.geometry || {},
                additionalObjects: model.additionalObjects || []
            };

            // 将数据转换为JSON字符串
            const jsonString = JSON.stringify(exportData, null, 2);

            // 使用数据URI方法下载
            const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonString);
            const fileName = `${exportData.name || 'model'}.json`;

            const link = document.createElement('a');
            link.href = dataUri;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();

            setTimeout(() => {
                document.body.removeChild(link);
            }, 100);
        } catch (error) {
            console.error('下载JSON模型失败:', error);
            alert('下载模型失败: ' + error.message);
        }
    };

    // 下载其他格式模型
    const downloadModelAs = async (format) => {
        if (!model) return;
        handleCloseDownloadMenu();

        try {
            setDownloadInProgress(true);
            await exportModel(model, format);
        } catch (error) {
            console.error(`下载${format.toUpperCase()}模型失败:`, error);
            alert(`下载${format.toUpperCase()}模型失败: ${error.message}`);
        } finally {
            setDownloadInProgress(false);
        }
    };

    return (
        <Paper sx={{ p: 3, borderRadius: 2, mb: 4 }}>
            {showInfo && (
                <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            {model.name || '3D模型预览'}
                        </Typography>
                        {model.description && (
                            <Typography variant="body2" color="text.secondary">
                                {model.description}
                            </Typography>
                        )}
                    </Box>
                    <Tooltip title="下载模型">
                        <IconButton
                            onClick={handleOpenDownloadMenu}
                            color="primary"
                            disabled={downloadInProgress}
                        >
                            <FileDownloadIcon />
                        </IconButton>
                    </Tooltip>

                    {/* 下载格式菜单 */}
                    <Menu
                        anchorEl={downloadMenuAnchor}
                        open={Boolean(downloadMenuAnchor)}
                        onClose={handleCloseDownloadMenu}
                        anchorOrigin={{
                            vertical: 'bottom',
                            horizontal: 'right',
                        }}
                        transformOrigin={{
                            vertical: 'top',
                            horizontal: 'right',
                        }}
                    >
                        <MenuItem onClick={downloadJsonModel}>
                            <ListItemIcon>
                                <FileDownloadIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>JSON格式</ListItemText>
                        </MenuItem>
                        <MenuItem onClick={() => downloadModelAs('obj')}>
                            <ListItemIcon>
                                <ViewInArIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>OBJ格式</ListItemText>
                        </MenuItem>
                        <MenuItem onClick={() => downloadModelAs('stl')}>
                            <ListItemIcon>
                                <ViewInArIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>STL格式</ListItemText>
                        </MenuItem>
                        <MenuItem onClick={() => downloadModelAs('glb')}>
                            <ListItemIcon>
                                <ViewInArIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>GLB格式</ListItemText>
                        </MenuItem>
                    </Menu>
                </Box>
            )}

            <Paper
                elevation={1}
                sx={{
                    width: '100%',
                    height: height,
                    overflow: 'hidden',
                    borderRadius: 2
                }}
            >
                <Canvas>
                    <ModelRenderer model={model} />
                </Canvas>
            </Paper>

            {!showInfo && (
                <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
                    <Button
                        variant="outlined"
                        startIcon={<FileDownloadIcon />}
                        onClick={handleOpenDownloadMenu}
                        size="small"
                        disabled={downloadInProgress}
                    >
                        下载模型
                    </Button>

                    {/* 下载格式菜单（移动版） */}
                    <Menu
                        anchorEl={downloadMenuAnchor}
                        open={Boolean(downloadMenuAnchor)}
                        onClose={handleCloseDownloadMenu}
                        anchorOrigin={{
                            vertical: 'bottom',
                            horizontal: 'right',
                        }}
                        transformOrigin={{
                            vertical: 'top',
                            horizontal: 'right',
                        }}
                    >
                        <MenuItem onClick={downloadJsonModel}>
                            <ListItemIcon>
                                <FileDownloadIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>JSON格式</ListItemText>
                        </MenuItem>
                        <MenuItem onClick={() => downloadModelAs('obj')}>
                            <ListItemIcon>
                                <ViewInArIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>OBJ格式</ListItemText>
                        </MenuItem>
                        <MenuItem onClick={() => downloadModelAs('stl')}>
                            <ListItemIcon>
                                <ViewInArIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>STL格式</ListItemText>
                        </MenuItem>
                        <MenuItem onClick={() => downloadModelAs('glb')}>
                            <ListItemIcon>
                                <ViewInArIcon fontSize="small" />
                            </ListItemIcon>
                            <ListItemText>GLB格式</ListItemText>
                        </MenuItem>
                    </Menu>
                </Box>
            )}
        </Paper>
    );
};

export default ModelViewer; 